<!-- 组织-组织机构管理-组织机构页面 -->
<template>
  <a-modal
    width="60%"
    :visible="visible"
    @ok="handleOk"
    @cancel="handleCancel"
    :mask-closable="false"
    title-align="center"
  >
    <template #title>
      <div>选择人员</div>
    </template>
    <div class="container">
      <div class="main">
        <div class="left">
          <div class="header">
            <div class="header-front">
              <a-space>
                <a-input-search
                  placeholder="请输入"
                  style="margin-bottom: 8px; max-width: 240px"
                  v-model="searchKey"
                />
              </a-space>
            </div>
          </div>
          <div
            style="
              height: calc(100% - 40px);
              border-right: 1px solid #e4e4e4;
              overflow: auto;
            "
          >
            <a-tree
              :data="treeData"
              :fieldNames="{
                key: 'id',
                title: 'name',
                children: 'children'
              }"
            >
              <template #title="nodeData">
                <template
                  v-if="((index = getMatchIndex(nodeData?.name)), index < 0)"
                >
                  <template
                    v-if="nodeData.node === '部门' || nodeData.node === '公司'"
                  >
                    {{ nodeData?.name }}
                  </template>
                  <template v-else>
                    <a-checkbox
                      @change="changePersonnel($event as boolean, nodeData)"
                      :model-value="personnelIds"
                      :value="nodeData.id"
                    >
                      {{ nodeData?.name }}</a-checkbox
                    >
                  </template>
                </template>
                <span v-else>
                  <template
                    v-if="nodeData.node === '部门' || nodeData.node === '公司'"
                  >
                    {{ nodeData?.name?.substr(0, index) }}
                    <span style="color: var(--color-primary-light-4)">
                      {{ nodeData?.name?.substr(index, searchKey.length) }}
                    </span>
                    {{ nodeData?.name?.substr(index + searchKey.length) }}
                  </template>
                  <template v-else>
                    <a-checkbox
                      @change="changePersonnel($event as boolean, nodeData)"
                      :model-value="personnelIds"
                      :value="nodeData.id"
                    >
                      {{ nodeData?.name?.substr(0, index) }}
                      <span style="color: var(--color-primary-light-4)">
                        {{ nodeData?.name?.substr(index, searchKey.length) }}
                      </span>
                      {{
                        nodeData?.name?.substr(index + searchKey.length)
                      }}</a-checkbox
                    >
                  </template>
                </span>
              </template>
            </a-tree>
          </div>
        </div>
        <div class="right">
          <div class="header">
            <div class="header-front">
              <a-space style="justify-content: space-between" fill>
                <div>已选：{{ personnelData.length }}</div>
                <div style="cursor: pointer" @click="delPersonnel(2)">
                  全部清除
                </div>
              </a-space>
            </div>
          </div>
          <a-space direction="vertical" fill>
            <template v-for="personnel in personnelData" :key="personnel.id">
              <div class="personnel">
                <div>
                  <a-avatar
                    :style="{ backgroundColor: '#168CFF', marginRight: '10px' }"
                    shape="square"
                  >
                    {{ personnel.name }}
                  </a-avatar>
                  {{ personnel.name }}
                </div>
                <icon-close
                  style="cursor: pointer"
                  :size="20"
                  @click="delPersonnel(1, personnel)"
                />
              </div>
            </template>
          </a-space>
        </div>
      </div>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
import { GetOrganizationList } from '@/apis/management/organization/organizationManagement';
import { GetSectionPersonnel } from '@/apis/management/human/baseSetting/leaveSetting';
import { cloneDeep } from 'lodash';

const props = withDefaults(
  defineProps<{
    selectedIds: number[]; // 选中的ids
  }>(),
  {}
);
const visible = ref(false);
const searchKey = ref('');
const originTreeData: any = reactive({ data: [] });
const show = () => {
  visible.value = true;
};

const emit = defineEmits(['changePersonnel']);
const treeData = computed(() => {
  if (!searchKey.value) return originTreeData.data;
  return searchData(searchKey.value);
});
function searchData(keyword: any) {
  const loop = (data: any) => {
    const result: any = [];
    data?.forEach((item: any) => {
      if (item.name.toLowerCase().indexOf(keyword.toLowerCase()) > -1) {
        result.push({ ...item });
      } else if (item.children) {
        const filterData = loop(item.children);
        if (filterData.length) {
          result.push({
            ...item,
            children: filterData
          });
        }
      }
    });
    return result;
  };
  return loop(originTreeData.data);
}
let flag = false;
watch(
  () => props.selectedIds,
  (val) => {
    personnelIds.length = 0;
    personnelData.length = 0;
    if (originTreeData.data[0]) {
      watchSelectedIds(originTreeData.data[0]);
      val?.forEach((ele) => {
        if (!personnelIds?.includes(ele)) personnelIds.push(ele);
      });
      const map = new Map();
      const newArr = personnelData.filter(
        (v: any) => !map.has(v.id) && map.set(v.id, v)
      );
      personnelData.length = 0;
      newArr?.forEach((ele: any) => {
        personnelData.push(ele);
      });
    } else {
      flag = true;
    }
  }
);
const watchSelectedIds = (data: any) => {
  if (
    props.selectedIds?.includes(data.id) &&
    !personnelIds?.includes(data.id)
  ) {
    personnelData.push(data);
  }
  if (data.children && data.children.length !== 0) {
    data.children?.forEach((ele: any) => {
      watchSelectedIds(ele);
    });
  }
};

function getMatchIndex(title: any) {
  if (!searchKey.value) return -1;
  return title.toLowerCase().indexOf(searchKey.value.toLowerCase());
}

const init = async () => {
  const res = await GetOrganizationList(null);
  originTreeData.data = [await changeData(cloneDeep(res[0]))];
  if (flag) {
    watchSelectedIds(originTreeData.data[0]);
    props.selectedIds?.forEach((ele) => {
      if (!personnelIds?.includes(ele)) personnelIds.push(ele);
    });
    const map = new Map();
    const newArr = personnelData.filter(
      (v: any) => !map.has(v.id) && map.set(v.id, v)
    );
    personnelData.length = 0;
    newArr?.forEach((ele: any) => {
      personnelData.push(ele);
    });
    emit(
      'changePersonnel',
      cloneDeep({ ids: personnelIds, data: personnelData })
    );
  }
};

const changeData = async (data: any) => {
  if (data.children && data.children.length !== 0) {
    for (let index = 0; index < data.children.length; index++) {
      const element = await changeData(data.children[index]);
      data.children[index] = element;
    }
  }
  if (data.node === '部门' || data.node === '公司') {
    const personnelData = await GetSectionPersonnel({
      type: data.node === '部门' ? 2 : 1,
      typeName: data.id
    });
    personnelData?.forEach((ele: any) => {
      ele.node = '人';
    });
    if (!data.children) {
      data.children = personnelData.map(
        ({ id, name, node, departmentId }: any) => ({
          id,
          name,
          node,
          departmentId
        })
      );
    } else {
      personnelData?.forEach((ele: any) => {
        data.children.push({
          id: ele.id,
          name: ele.name,
          node: ele.node,
          departmentId: ele.departmentId
        });
      });
    }
  }
  return {
    id: data.id,
    name: data.name,
    node: data.node,
    children: data.children
  };
};

const personnelIds: number[] = reactive([]);
const personnelData: any = reactive([]);

const changePersonnel = (flag: boolean, data: any) => {
  if (flag) {
    if (!personnelIds.some((ele) => ele === data.id)) {
      personnelIds.push(data.id);
      personnelData.push(data);
    }
  } else {
    if (personnelIds.some((ele) => ele === data.id)) {
      personnelIds.splice(
        personnelIds.findIndex((ele) => ele === data.id),
        1
      );
      personnelData.splice(
        personnelData.findIndex((ele: any) => ele.id === data.id),
        1
      );
    }
  }
};

const delPersonnel = (type: 1 | 2, data?: any) => {
  if (type === 1) {
    personnelIds.splice(
      personnelIds.findIndex((ele) => ele === data.id),
      1
    );
    personnelData.splice(
      personnelData.findIndex((ele: any) => ele.id === data.id),
      1
    );
  } else {
    personnelIds.length = 0;
    personnelData.length = 0;
  }
};

init();
// 保存
const handleOk = () => {
  emit(
    'changePersonnel',
    cloneDeep({ ids: personnelIds, data: personnelData })
  );
  delPersonnel(2);
  visible.value = false;
};

// 取消
const handleCancel = () => {
  delPersonnel(2);
  visible.value = false;
};
defineExpose({
  show
});
</script>

<style lang="less" scoped>
.container {
  height: 500px;
  // padding: 10px 20px;
  .header {
    width: 100%;
    height: 40px;
    border-bottom: 1px solid #e4e4e4;
    display: flex;
    justify-content: space-between;
    padding: 0 10px;
    align-items: center;
    &-front {
      width: calc(100% - 20px);
      position: relative;
      line-height: 30px;
    }
    .commonBtns {
      background-color: rgb(var(--primary-1));
    }
  }
  .main {
    display: flex;
    width: 100%;
    height: calc(100% - 40px);
    .left {
      padding-top: 20px;
      height: 100%;
      width: 40%;
      // border-right: 1px solid #e4e4e4;
      // overflow: auto;
    }
    .right {
      padding-top: 20px;
      height: 100%;
      width: 60%;
      // border-right: 1px solid #e4e4e4;
      // overflow: auto;
      .personnel {
        margin: 2px 5px 0 5px;
        padding: 5px;
        display: flex;
        align-items: center;
        width: 100%;
        justify-content: space-between;
        background: #f2f2f2;
        font-size: 16px;
      }
    }
  }
}
</style>
